package com.powernode.config;

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign拦截器
 * 作用：处理服务之间调用没有token的情况
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(requestAttributes)) {
            // 获取请求对象
            // request是上一个请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断是否为空
            if (ObjectUtil.isNotNull(request)) {
                // 将当前请求对象头中的token传递到下一个请求对象的请求头中
                // requestTemplate是发起调用另外一个服务的请求对象，该请求对象的头中没有token
                requestTemplate.header(AuthConstants.AUTHORIZATION,request.getHeader(AuthConstants.AUTHORIZATION));
            }
        }
        requestTemplate.header(AuthConstants.AUTHORIZATION,"bearer 019639fb-ffba-4083-90ae-fb7b188ccaaf");
    }
}
